package 算法.leetcode.bytedance.字符串;

/**
 * @author lchenglong
 * @date 2023/2/9
 */
public class 最长公共前缀 {

    public static class Solution {

        public static void main(String[] args) {
            Solution solution = new Solution();

        }

        public String longestCommonPrefix(String[] strs) {
            // 边界条件
            if (strs == null || strs.length == 0) return "";
            if (strs.length == 1) return strs[0];
            // 游标
            int index = 0;
            // 存放公共前缀
            StringBuilder sb = new StringBuilder();
            while (true) {
                // 退出标志位
                boolean exitFlag = false;
                // 公共前缀字符
                Character c = null;
                // 遍历数组
                for (int i = 0; i < strs.length; i++) {
                    if (index >= strs[i].length()) {
                        // 超过某一个字符串长度,退出循环
                        exitFlag = true;
                        break;
                    }
                    c = (c == null) ? c = strs[i].charAt(index) : c;
                    if (c != strs[i].charAt(index)){
                        exitFlag = true;
                        break;
                    }
                }
                // 不满足公共前缀了,退出
                if (exitFlag)break;
                sb.append(c);
                index++;

            }
            return sb.toString();

        }
    }
}
